﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace Al_FrameWork
{
    /// <summary>
    /// 检测场景
    /// </summary>
    public class StartUp : MonoBehaviour
    {
        /// <summary>
        /// 日志
        /// </summary>
        public StringBuilder str;

        /// <summary>
        /// 日志内容
        /// </summary>
        public Text text_log;

        /// <summary>
        /// 更新
        /// </summary>
        public Button btn_update;

        /// <summary>
        /// 下载文本
        /// </summary>
        public Text text_downLoad;

        /// <summary>
        /// 进度条图片
        /// </summary>
        public Image img_download_progress;

        /// <summary>
        /// 进度文本
        /// </summary>
        public Text text_progress;

        /// <summary>
        /// 热更新板块
        /// </summary>
        public Transform panel_update;

        /// <summary>
        /// 进入登录界面按钮
        /// </summary>
        public Button btn_enter;

        /// <summary>
        /// 当前已下载所有AB包的大小的总和
        /// </summary>
        private long currentDownloadedABTotalSize;

        /// <summary>
        /// 当前已经下载重试次数
        /// </summary>
        private int failCount;

        /// <summary>
        /// 当前要下载的AB信息
        /// </summary>
        private ABInfo currentDownloadAB;


        public Camera _camera;
        
        /// <summary>
        /// Start
        /// </summary>
        /// <returns></returns>
        private IEnumerator Start()
        {
            InitData();
            InitGame();
            InitUI();
            //下载比对文件
            string requestABCompareInfoUrl = string.Format("{0}/{1}/{2}", GameConfig.UpdateUrl,
                GlobalFunctions.GetCurrentRunningPF(), GameConfig.ABCompareInfo);
            string localSaveABCompareInfoPath = GlobalFunctions.GetPersistentDataPath(GameConfig.ABCompareTempInfo);
            WWWManager.Instance.BackgroundDownload(requestABCompareInfoUrl, localSaveABCompareInfoPath,
                ABCompareInfoDownloadFinish);
            yield return null;
        }

        /// <summary>
        /// 比对文件下载回调
        /// </summary>
        /// <param name="downloadStatus"></param>
        private void ABCompareInfoDownloadFinish(DownloadStatus downloadStatus)
        {
            switch (downloadStatus)
            {
                case DownloadStatus.Done:
                    //下载完成比对版本获取差异
                    CheckUpdateManager.Instance.CheckUpdate();
                    ActivePanelUpdate();
                    print("需要更新的文件个数--------"+CheckUpdateManager.Instance.GetNeedDownLoadInfo().Count);
                    if (CheckUpdateManager.Instance.GetNeedDownLoadInfo().Count == 0)
                    {
                        UpdateFinish();
                    }

                    break;
                case DownloadStatus.Failed:
                    // ActivePanelUpdate();
                    // UpdateFinish();
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 下载完成更新文件
        /// </summary>
        private void UpdateFinish()
        {
            //修改比对文件名字
            string remoteABPath = Application.persistentDataPath + "/ABCompareInfo_Temp.txt";
            string localABPath = Application.persistentDataPath + "/ABCompareInfo.txt";
            if (File.Exists(localABPath))
            {
                File.Delete(localABPath);
            }

            //删除原有文件
            if (File.Exists(remoteABPath))
            {
                GlobalFunctions.LOG("remoteABPath------" + remoteABPath);
                GlobalFunctions.LOG("localABPath------------" + localABPath);
                GlobalFunctions.ReNameFile(remoteABPath, localABPath);
                GameDownLoadABFinish();
                ResourceManager.Instance.ClearAllAssetBundle();
                StartCoroutine(InitLuaAssetBundle());
            }
        }


        /// <summary>
        /// 初始化LuaAB包
        /// </summary>
        /// <returns></returns>
        IEnumerator InitLuaAssetBundle()
        {
            OnLoadLuaAssetBundle();
            XLuaManager.Instance.Init();
            XLuaManager.Instance.StartHotfix();
            yield return null;
        }

        /// <summary>
        /// ResetXLuaEnv
        /// </summary>
        void ResetXLuaEnv()
        {
            XLuaManager.Instance.Restart();
            XLuaManager.Instance.StartHotfix();
        }


        /// <summary>
        /// OnLoadLuaAssetBundle
        /// </summary>
        private void OnLoadLuaAssetBundle()
        {
            string luaAssetBundleUrl =
                Path.Combine(GlobalFunctions.GetPersistentDataPath(), GameConfig.LuaAssetBundleName);
            AssetBundle assetBundle = AssetBundle.LoadFromFile(luaAssetBundleUrl);
            ResourceManager.Instance.AddAssetBundle(assetBundle);

            //测试
            string texturesAssetBundleUrl =
                Path.Combine(GlobalFunctions.GetPersistentDataPath(), GameConfig.TexturesAssetBundleName);
            AssetBundle assetBundlenew = AssetBundle.LoadFromFile(texturesAssetBundleUrl);
            ResourceManager.Instance.AddAssetBundle(assetBundlenew);
            //
            // ResourceManager.Instance.LoadSpriteAtlas("AssetBundles/Textures/Cards/Cards.png");
        }


        /// <summary>
        /// OnDestroy
        /// </summary>
        private void OnDestroy()
        {
            GlobalFunctions.LOG("OnDestory");
            StopAllCoroutines();
        }

        /// <summary>
        /// 初始化UI
        /// </summary>
        private void InitUI()
        {
            btn_enter.onClick.RemoveAllListeners();
            btn_enter.onClick.AddListener(btn_enter_clicked);
            btn_update.onClick.RemoveAllListeners();
            btn_update.onClick.AddListener(btn_update_clicked);
            panel_update.gameObject.SetActive(false);
            btn_enter.gameObject.SetActive(false);
        }

        /// <summary>
        /// 初始化游戏
        /// </summary>
        private void InitGame()
        {
            CheckUpdateManager.Instance.InitData();
        }

        /// <summary>
        /// InitData
        /// </summary>
        private void InitData()
        {
            str = new StringBuilder();
            currentDownloadedABTotalSize = 0;
            failCount = 0;
        }
    

        /// <summary>
        /// btn_enter_clicked
        /// </summary>
        private void btn_enter_clicked()
        {
            GlobalFunctions.LOG("btn_enter_clicked");
            ResetXLuaEnv();
            ResourceManager.Instance.LoadScene("Fight");
        }

        /// <summary>
        /// 每一帧去检查
        /// </summary>
        private void Update()
        {
            if (CheckUpdateManager.Instance.NeedDownLoadFileCounts() != 0)
            {
                UpdateDownLoadProress();
            }

            string value = GlobalFunctions.GetLatestLog();
            if (string.IsNullOrEmpty(value) ||
                string.IsNullOrWhiteSpace(value))
            {
                return;
            }
            //
            // str.AppendLine(value);
            // text_log.text = str.ToString();
        }

        /// <summary>
        /// GameDownLoadABFinish
        /// </summary>
        private void GameDownLoadABFinish()
        {
            panel_update.gameObject.SetActive(false);
            btn_enter.gameObject.SetActive(true);
        }

        /// <summary>
        /// 所有AB包下载完毕
        /// </summary>
        private void UpdateDownLoadProress()
        {
            long totalDownLoadSize = CheckUpdateManager.Instance.NeedDownLoadTotalSize();
            ///当前下载的文件个数
            int currentNeedDownloadedFileCounts = CheckUpdateManager.Instance.NeedDownLoadFileCounts() -
                                                  CheckUpdateManager.Instance.GetNeedDownLoadInfo().Count;

            // GlobalFunctions.LOG("{0}/{1}", CheckUpdateManager.Instance.GetNeedDownLoadInfo().Count,
            // CheckUpdateManager.Instance.NeedDownLoadFileCounts());
            float value = (float)currentNeedDownloadedFileCounts /
                          (float)CheckUpdateManager.Instance.NeedDownLoadFileCounts();
            if (value >= 1)
            {
                text_downLoad.text = "更新完成";
                img_download_progress.GetComponent<Image>().fillAmount = value;
                text_progress.text = string.Format("{0:0}", value * 100) + "%";
            }
            else
            {
                if (currentDownloadAB == null)
                    return;


                string content = "下载文件[" + currentDownloadAB.FileName + "],进度[" + currentNeedDownloadedFileCounts +
                                 "/" +
                                 CheckUpdateManager.Instance.NeedDownLoadFileCounts() +
                                 "],剩余大小" + GlobalFunctions.FormatFileSize(totalDownLoadSize -
                                                                           currentDownloadedABTotalSize);
                text_downLoad.text = content;
                GlobalFunctions.LOG(content);
                text_progress.text = string.Format("{0:0}", value * 100) + "%";
                img_download_progress.GetComponent<Image>().fillAmount = value;
            }
        }

        /// <summary>
        /// btn_update_clicked
        /// </summary>
        private void btn_update_clicked()
        {
            btn_update.gameObject.SetActive(false);
            panel_update.gameObject.SetActive(true);
            UpdateResource();
        }

        /// <summary>
        /// 下载需要更新的资源
        /// </summary>
        private void UpdateResource()
        {
            if (CheckUpdateManager.Instance.GetNeedDownLoadInfo().Count > 0)
            {
                ABInfo abInfo = CheckUpdateManager.Instance.GetNeedDownLoadInfo()[0];
                currentDownloadAB = abInfo;
                string requestPath = string.Format("{0}/{1}/{2}", GameConfig.UpdateUrl,
                    GlobalFunctions.GetCurrentRunningPF(), abInfo.FileName);

                string savePath = GlobalFunctions.GetPersistentDataPath(abInfo.FileName);
                WWWManager.Instance.BackgroundDownload(requestPath, savePath, DoneUpdateResource);
            }
            else
            {
                UpdateFinish();
            }
        }

        /// <summary>
        /// 一个文件下载完毕
        /// </summary>
        /// <param name="downloadStatus"></param>
        private void DoneUpdateResource(DownloadStatus downloadStatus)
        {
            switch (downloadStatus)
            {
                case DownloadStatus.Done:
                    CheckAllIsUpdateDone();
                    break;
                case DownloadStatus.Failed:
                    failCount++;
                    if (failCount >= GameConfig.downloadFailCount)
                    {
                        GlobalFunctions.Err("下载失败{0}重试第{1}次", currentDownloadAB.FileName, failCount);
                        UpdateResource();
                    }
                    else
                    {
                        UpdateResource();
                    }

                    break;
            }
        }

        /// <summary>
        /// 检查是否已经全部下载完成 并更新状态
        /// </summary>
        private void CheckAllIsUpdateDone()
        {
            failCount = 0;
            currentDownloadedABTotalSize += currentDownloadAB.Size;
            CheckUpdateManager.Instance.GetNeedDownLoadInfo().RemoveAt(0);
            if (CheckUpdateManager.Instance.GetNeedDownLoadInfo().Count == 0)
            {
                UpdateFinish();
            }
            else
            {
                UpdateResource();
            }
        }


        /// <summary>
        /// ActivePanelUpdate
        /// </summary>
        /// <param name="isShow"></param>
        private void ActivePanelUpdate()
        {
            List<ABInfo> needDownLoad = CheckUpdateManager.Instance.GetNeedDownLoadInfo();
            if (needDownLoad.Count > 0)
            {
                int totalFiles = needDownLoad.Count;
                text_downLoad.text = "需要下载" + totalFiles + "个文件，总大小" +
                                     GlobalFunctions.FormatFileSize(CheckUpdateManager.Instance
                                         .NeedDownLoadTotalSize());
                img_download_progress.GetComponent<Image>().fillAmount = 0;
                btn_update.gameObject.SetActive(true);
                panel_update.gameObject.SetActive(false);
                btn_enter.gameObject.SetActive(false);
            }
            else
            {
                text_downLoad.text = "已最新版本无需更新";
                btn_update.gameObject.SetActive(false);
                panel_update.gameObject.SetActive(false);
                btn_enter.gameObject.SetActive(true);
            }
        }
    }
}